//
//  WBOAuthViewController.swift
//  WeiBo
//
//  Created by chenguanglei on 16/11/27.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class WBOAuthViewController: UIViewController,UIWebViewDelegate {

    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

   
        view.backgroundColor = UIColor.white
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.plain, target: self, action: #selector(close))
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.plain, target: self, action: #selector(aotuFill))
        
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=180663250&redirect_uri=http://www.weibo.com"
        
        let url = URL(string: urlString)!
        
        let resquest = URLRequest(url: url)
        
        webView.loadRequest(resquest)
        
        
    }
    

    @objc private func aotuFill(){
    
        
        let js = "document.getElementById('userId').value = 'chenguanglei@sina.cn';document.getElementById('passwd').value = '19941001';"
        
        
        webView.stringByEvaluatingJavaScript(from: js)
    
    }
    
    
    func close(){
    
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
        
    }
    
    
    //webViewDelegate
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        
        if let urlString = request.url?.absoluteString {
            
            
            //截取字符第一种方式
            if urlString.hasPrefix("http://www.weibo.com/?") {
                
                let codeString = urlString.components(separatedBy: "=").last
                
                
                if let code = codeString {
                    
                    WBUserAccount.shareInstance.loadToken(code: code, success: { 
                        
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationChangeVC), object: self)
                        
                        
                        self.close()
                        
                        print("成功了")
                        
                        }, fail: { 
                          
                            print("失败了")
                    })
                    

                }
                
                
            }
            
            
//            //截取字符串第二种方式
//            if let query = request.url?.query{
//                
//                let code = query.substring(from: "code=".endIndex)
//                
//                loadToken(code: code)
//                
//            }
//            
            
            
        }
        
        
        
        
        return true
    }
    
    
    
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.showError(withStatus: error.localizedDescription)
    }
    
    
    
    deinit {
        
        print("授权控制器死了")
        
    }
    
    
    
}
